package com.autoMobile.servlet;
import com.autoMobile.bean.Vehicle;
import com.autoMobile.dao.VehicleDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Date;
import java.util.List;

@WebServlet(name = "UpdateVehServlet", value = "/Veh/UpdateVehServlet")
public class UpdateVehServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UpdateVehServlet-get:cs");
        String in = request.getParameter("in");
        List<Vehicle> list = (List<Vehicle>) request.getSession().getAttribute("VehList");
        request.setAttribute("editVeh",list.get(Integer.parseInt(in)));
        request.getRequestDispatcher("/admin/eit_vehicle.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UpdateVehServlet-post:cs");
        Vehicle vehicle = new Vehicle(request.getParameter("licensePlate"),request.getParameter("model"),
                request.getParameter("status"),request.getParameter("currentDriver"),
                Date.valueOf(request.getParameter("purchaseDate")),Integer.parseInt(request.getParameter("totalMileage")));
        vehicle.setId(Integer.parseInt(request.getParameter("id")));
        HttpSession session = request.getSession();
        if (vehicle.getId() != 0){
            int success = VehicleDao.updateVehicle(vehicle);
            if (success!=0) {
                session.setAttribute("message", "更新成功");
            } else {
                session.setAttribute("message", "更新失败");
            }
           response.sendRedirect(request.getContextPath()+"/Veh/VehListServlet");
        }else {
            int positionId = VehicleDao.addVehicle(vehicle);
            if (positionId > 0) {
                session.setAttribute("message", "信息添加成功");
            } else {
                session.setAttribute("message", "添加信息错误");
            }
            response.sendRedirect(request.getContextPath()+"/Veh/VehListServlet");
        }
    }
}
